package com.cloud.user.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.cloud.api.BlogServiceApi;
import com.cloud.api.pojo.*;
import com.cloud.common.constant.Constants;
import com.cloud.common.exception.BlogException;
import com.cloud.common.pojo.Result;
import com.cloud.common.utils.*;
import com.cloud.user.convert.BeanConvert;
import com.cloud.user.dataobject.UserInfo;
import com.cloud.user.mapper.UserInfoMapper;
import com.cloud.user.service.UserService;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private BlogServiceApi blogServiceApi;

    @Autowired
    private Redis redis;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private static final long EXPIRE_TIME = 14*24*60*60;

    private static final String USER_PREFIX = "user";

    @Override
    public UserLoginResponse login(UserInfoRequest user) {
        //验证账号密码是否正确
        UserInfo userInfo = queryUserInfo(user.getUserName());
        if (userInfo==null || userInfo.getId()==null){
            throw new BlogException("用户不存在");
        }
//        if (!user.getPassword().equals(userInfo.getPassword())){
//            throw new BlogException("用户密码不正确");
//        }
        if (!SecurityUtil.verify(user.getPassword(),userInfo.getPassword())){
            throw new BlogException("用户密码不正确");
        }
        //账号密码正确的逻辑
        Map<String,Object> claims = new HashMap<>();
        claims.put("id", userInfo.getId());
        claims.put("name", userInfo.getUserName());

        String jwt = JWTUtils.genJwt(claims);
        return new UserLoginResponse(userInfo.getId(), jwt);
    }



    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        UserInfo userInfo = selectUserInfoById(userId);
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public UserInfoResponse selectAuthorInfoByBlogId(Integer blogId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        //1. 根据博客ID, 获取作者ID
        Result<BlogInfoResponse> blogDetail = blogServiceApi.getBlogDetail(blogId);
        //2. 根据作者ID, 获取作者信息
        if (blogDetail == null||blogDetail.getData()==null){
            throw new BlogException("博客不存在");
        }
        UserInfo userInfo = selectUserInfoById(blogDetail.getData().getUserId());
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public Integer register(UserInfoRegisterRequest registerRequest) {
        checkUserInfo(registerRequest);

        if(!RegexUtil.checkMail(registerRequest.getEmail())){
            throw new BlogException("邮箱格式不合法");
        }
        if(!RegexUtil.checkURL(registerRequest.getGithubUrl())){
            throw new BlogException("GithubUrl格式不合法");
        }
        UserInfo userInfo = BeanConvert.convertUserInfoByEncrypt(registerRequest);
        try{
            int result = userInfoMapper.insert(userInfo);
            if(result == 1){
                redis.set(buildKey(userInfo.getUserName()), JsonUtil.toJson(userInfo),EXPIRE_TIME);
                //发送消息
                userInfo.setPassword("");
                rabbitTemplate.convertAndSend(Constants.USER_EXCHANGE_NAME,"",JsonUtil.toJson(userInfo));
                return userInfo.getId();
            }else{
                throw new BlogException("用户注册失败");
            }
        }catch (Exception e){
            log.error("用户注册失败,e",e);
            throw new BlogException("用户注册失败");
        }

    }

    private String buildKey(String userName) {
        return redis.buildKey(USER_PREFIX,userName);
    }

    private void checkUserInfo(UserInfoRegisterRequest registerRequest) {
        UserInfo userInfo = selectUserInfoByName(registerRequest.getUserName());
        if(userInfo!=null){
            throw new BlogException("用户已存在");
        }
    }
    private UserInfo queryUserInfo(String userName) {
        String key = buildKey(userName);
        Boolean exists = redis.hasKey(key);
        if(exists){
            log.info("从redis中读取数据,userName:{}",userName);
            String userJson = redis.get(key);
            UserInfo userInfo = JsonUtil.parseJson(userJson, UserInfo.class);
            return userInfo == null?selectUserInfoByName(userName):userInfo;

        }else {
            log.info("从mysql中读取数据,userName:{}",userName);
             UserInfo userInfo = selectUserInfoByName(userName);
             redis.set(key,JsonUtil.toJson(userInfo),EXPIRE_TIME);
             return userInfo;
        }

    }
    public UserInfo selectUserInfoByName(String userName) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserName, userName).eq(UserInfo::getDeleteFlag, 0));
    }
    private UserInfo selectUserInfoById(Integer userId) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getId, userId).eq(UserInfo::getDeleteFlag, 0));
    }
}
